/**
 * sockettj  -- A php language extension application for network socket.
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <unistd.h>
#include "sockettj.h"

static void get_hostname(char* url, char* result) {
	char * temp = strstr(url, "//");
	temp += 2;
	int i;
	for (i = 0; i < strlen(temp); i++) {
		if ('/' == temp[i] || ':' == temp[i]) {
			temp[i] = '\0';
		}
	}
	strcpy(result, temp);
}
static int get_port(const char* url) {
	int port = 80;
	char * temp = strstr(url, ":");
	temp++;
	temp = strstr(temp, ":");
	if (NULL != temp) {
		temp++;
		port = atoi(temp);
		if (80 > port) {
			port = 80;
		}
	}
	return port;
}

/**
 * HTTP 协议的客户端
 *
 * 请求方法（所有方法全为大写）有多种，各个方法的解释如下：
 * GET     请求获取Request-URI所标识的资源
 * POST    在Request-URI所标识的资源后附加新的数据
 * HEAD    请求获取由Request-URI所标识的资源的响应消息报头
 * PUT     请求服务器存储一个资源，并用Request-URI作为其标识
 * DELETE  请求服务器删除Request-URI所标识的资源
 * TRACE   请求服务器回送收到的请求信息，主要用于测试或诊断
 * CONNECT 保留将来使用
 * OPTIONS 请求查询服务器的性能，或者查询与资源相关的选项和需求
 */
int http_get(char* url, char* method, char* post_data, char* result, int header) {
	char c;
	int i = 0;
	while (method[i]) {
		c = method[i];
		method[i] = toupper(c);
		i++;
	}
	char uri[255] = { '\0' };
	char* _uri = strstr(url, "//");
	_uri += 2;
	_uri = strstr(_uri, "/");
	strcpy(uri, _uri);

	int port = get_port(url);
	char ip[255] = { '\0' };
	get_hostname(url, ip);

	int fd = create_client_tcp(ip, port);

	char request[2048] = { '\0' };
	if (!strcmp("POST", method)) {
		char data[1024] = { '\0' };
		sprintf(data, "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: %i\r\n\r\n%s", strlen(post_data), post_data);
		sprintf(request, "%s %s HTTP/1.1\r\nHost: %s\r\n%s", method, uri, ip, data);
	} else {
		sprintf(request, "%s %s HTTP/1.1\r\nHost: %s\r\n\r\n", method, uri, ip);
	}
	printf("%s", request);
	send(fd, request, strlen(request) + 1, 0);
	int total_length = 0;
	int length;
	char buffer[2048] = { '\0' };
	do {
		length = recv(fd, buffer, 2048, 0);
		result[length] = '\0';
	} while (length != -1);
	if (header) {
		strcpy(result, buffer);
	} else {
		char* temp = strstr(buffer, "\r\n\r\n");
		temp += 4;
		strcpy(result, temp);
	}
	close(fd);
	return 0;
}

